import datetime

from django.db.models import Sum, F
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from appointment.models import Appointment
from apply.models import Apply
from medicine_use.models import Medicine_use
from prescription.models import Prescription
from medicine.models import Medicine


# 返回待缴费列表
class PayList(APIView):
    def post(self, request):
        patient_id = request.data.get('patient_id')

        if not patient_id:
            return Response({"error": "需要提供病人id"},
                            status=status.HTTP_400_BAD_REQUEST)

        appointments = Appointment.objects.filter(patient_id=patient_id)
        print(appointments)
        data = []
        for a in appointments:
            print(a.id)
            if Appointment.objects.filter(id=a.id).exists():
                data.append({
                    "doctor_name": a.doctor.doctor_name,
                    "patient_id": a.patient_id,
                    "created_at": a.created_at,
                    "appointment_id": a.id,
                    "subject": a.subject,
                })

        return Response(data,
                        status=status.HTTP_200_OK)


class ReturnMRbyAppointment(APIView):
    def post(self, request):
        appointment_id = request.data.get('appointment_id')

        if not appointment_id:
            return Response({"error": "需要提供appointment_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        appointment = Appointment.objects.get(id=appointment_id)

        return Response({
            "medical_record_id": appointment.medical_record.id,
            "is_completed": appointment.medical_record.is_completed,
            "date": appointment.medical_record.date,
            "content": appointment.medical_record.content,
            "title": appointment.medical_record.title,
        },
            status=status.HTTP_200_OK)


class ReturnApplybyAppointment(APIView):
    def post(self, request):
        appointment_id = request.data.get('appointment_id')

        if not appointment_id:
            return Response({"error": "需要提供appointment_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        # appointment = Appointment.objects.get(id=appointment_id)
        applys = Apply.objects.filter(appointment_id=appointment_id)
        # 计算每个申请的总价格（数量 x 单价）
        # 计算所有申请记录的总价格
        total_price = applys.aggregate(
            total_price=Sum('price')  # 将所有 apply 记录的 price 字段加起来
        )['total_price'] or 0  # 如果没有记录，返回 0
        data = []
        for apply in applys:
            data.append({
                "id": apply.id,
                "name": apply.name,
                "position": apply.position,
                "description": apply.description,
                "time": apply.time,
                "status": apply.status,
                "result": apply.result,
                "doctor_name": apply.doctor_id.doctor_name,
                "price": apply.price,
                "pay_status": apply.pay_status,

            })
        is_all_paid = True  # 默认赋值为 True

        if applys:
            is_all_paid = all(apply.pay_status == "paid" for apply in applys)
        return Response({
            "apply_list": data,
            "is_all_paid": is_all_paid,
            "total_price": total_price

        },
            status=status.HTTP_200_OK)


class ReturnMedicalUsebyAppointment(APIView):
    def post(self, request):
        appointment_id = request.data.get('appointment_id')

        if not appointment_id:
            return Response({"error": "需要提供appointment_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        # appointment = Appointment.objects.get(id=appointment_id)
        # FIXME
        prescription_id = Prescription.objects.get(appointment=appointment_id)
        medical_uses = Medicine_use.objects.filter(prescription_id=prescription_id)
        # 计算每个药品的总价（数量 x 单价）
        total_price = medical_uses.annotate(
            total_item_price=F('num') * F('medicine_id__price')  # 每个药品的价格
        ).aggregate(
            total_price=Sum('total_item_price')  # 所有药品的总价
        )['total_price'] or 0  # 如果没有药品使用记录，返回 0
        data = []
        for medical_use in medical_uses:
            data.append({
                "id": medical_use.id,
                "medical_name": medical_use.medicine_id.name,
                "description": medical_use.description,
                "dosage": medical_use.dosage,
                "frequency": medical_use.frequency,
                "num": medical_use.num,
                "pay_status": medical_use.pay_status,
                "price": Medicine.objects.get(id=medical_use.medicine_id.id).price,

            })
        is_all_paid = True  # 默认赋值为 True

        if medical_uses:
            is_all_paid = all(medical_use.pay_status == "paid" for medical_use in medical_uses)
        return Response({
            "medical_use_list": data,
            "is_all_paid": is_all_paid,
            "total_price": total_price
        },
            status=status.HTTP_200_OK)


class PayApply(APIView):
    def post(self, request):
        appointment_id = request.data.get('appointment_id')

        if not appointment_id:
            return Response({"error": "需要提供appointment_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        # appointment = Appointment.objects.get(id=appointment_id)
        applys = Apply.objects.filter(appointment_id=appointment_id)
        for apply in applys:
            apply.pay_status = "paid"
            apply.save()

        return Response({"message": "已经付费"},
                        status=status.HTTP_200_OK)


class PayMedicine(APIView):
    def post(self, request):
        appointment_id = request.data.get('appointment_id')
        if not appointment_id:
            return Response({"error": "需要提供appointment_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        prescription_id = Prescription.objects.get(appointment=appointment_id)
        medical_uses = Medicine_use.objects.filter(prescription_id=prescription_id)
        for medical_use in medical_uses:
            medical_use.pay_status = "paid"
            medical_use.save()
        prescription = Prescription.objects.get(appointment_id=appointment_id)

        # 获取与 Prescription 相关的所有 Medicine_use 和 Apply 记录
        medicine_uses = Medicine_use.objects.filter(prescription_id=prescription)
        applies = Apply.objects.filter(appointment=appointment_id)

        # 检查所有 Medicine_use 和 Apply 的 pay_status 是否为 'paid'
        all_paid = True
        for medicine_use in medicine_uses:
            if medicine_use.pay_status != 'paid':
                all_paid = False
                break

        for apply in applies:
            if apply.pay_status != 'paid':
                all_paid = False
                break

        # 如果所有相关的记录都已付款，则更新 Prescription 状态
        if all_paid:
            prescription.status = '已完成'
            prescription.save()
        return Response({"message": "已经付费"},
                        status=status.HTTP_200_OK)


class RefundApply(APIView):
    def post(self, request):
        apply_id = request.data.get('apply_id')
        if not apply_id:
            return Response({"error": "需要提供apply_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        apply = Apply.objects.get(id=apply_id)
        if apply.pay_status == "pending":
            return Response({"error": "未缴费，无法退费"},
                            status=status.HTTP_400_BAD_REQUEST)
        if apply.pay_status == "refund":
            return Response({"error": "无法重复退费"},
                            status=status.HTTP_400_BAD_REQUEST)
        if apply.pay_status == "paid" and not apply.status:
            apply.pay_status = "refund"
            apply.status = "已退费"
            apply.save()
            return Response({"message": "退费完成"},
                            status=status.HTTP_200_OK)
        if apply.status == "已完成":
            return Response({"error": "检查已经完成，无法退费"},
                            status=status.HTTP_400_BAD_REQUEST)
        else:
            apply.pay_status = "refund"
            apply.save()
            return Response({"message": "退费完成"},
                            status=status.HTTP_200_OK)


class RefundMedicineUse(APIView):
    def post(self, request):
        medicine_use_id = request.data.get('medicine_use_id')
        if not medicine_use_id:
            return Response({"error": "需要提供medicine_use_id"},
                            status=status.HTTP_400_BAD_REQUEST)
        prescription = Medicine_use.objects.get(id=medicine_use_id).prescription_id
        if prescription.take_status == "untake":
            medicine_use = Medicine_use.objects.get(id=medicine_use_id)
            medicine_use.pay_status = "refund"
            medicine_use.save()
            # 把对应药品库存加回去
            medicine = Medicine.objects.get(id=medicine_use.medicine_id.id)
            medicine.counts = medicine.counts + medicine_use.num
            medicine.save()
            return Response({"message": "未取药,退费完成"},
                            status=status.HTTP_200_OK)
        else:

            return Response({"error": "已取药,需要到药房进行退款"},
                            status=status.HTTP_403_FORBIDDEN)
        # medicine_use = Medicine_use.objects.get(id=medicine_use_id)
        # if medicine_use.pay_status == "pending":
        #     return Response({"error": "未缴费，无法退费"},
        # if medicine_use.take_status == "refund":
        #     return Response({"error": "无法重复退费"},
        #                     status=status.HTTP_400_BAD_REQUEST)
        # if medicine_use.take_status == "take":
        #     return Response({"error": "检查已经完成，无法退费"},
        #                     status=status.HTTP_400_BAD_REQUEST)
        # else:
        #     medicine_use.pay_status = "refund"
        #     medicine_use.save()
        #     return Response({"message": "退费完成"},
        #                     status=status.HTTP_200_OK)
